//
//  HQRecordViewController.m
//  MobileiOS
//
//  Created by 郝庆松 on 2018/5/4.
//  Copyright © 2018年 PCITC. All rights reserved.
//

#import "HQRecordViewController.h"
#import "HQOrder.h"

@interface HQRecordViewController ()

@end

@implementation HQRecordViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationItem.title = @"记录";
    _orderStates = @"1";
    _dataSource = [[NSMutableArray alloc]init];
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem barButtonItemTitle:@"搜索" withTitleColor:[self colorHexValue:0x647180] withFont:16 withTarget:self withSelector:@selector(rightSearch)];
    [self setUpTopView];
    
    // 下拉刷新
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _pageNo=1;
        [self requestOrderList];
    }];
    [_tableView.mj_header beginRefreshing];
}

// 上拉刷新
-(void)addFooter{
    _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _pageNo++;
        [self requestOrderList];
    }];
}

/**
 搜索订单
 */
-(void)rightSearch{
    HQRecordSearchViewController *recordSearchDetailVc = [[HQRecordSearchViewController alloc]init];
    recordSearchDetailVc.hidesBottomBarWhenPushed = YES;
    recordSearchDetailVc.delegate = self;
    [self.navigationController pushViewController:recordSearchDetailVc animated:YES];
}

/**
 刷新界面
 */
-(void)reloadData{
    _pageNo = 1;
    [self requestOrderList];
}

/**
 请求订单列表数据
 */
-(void)requestOrderList{
    [self showHudText:@""];
    _tableView.backgroundView = nil;
    [HQNetWork requetParam:[HQParam orderOrderAllWithUserId:[UserModelManager userID] withOState:_orderStates search_txt:@"" page:[NSString stringWithFormat:@"%ld",_pageNo]] withMethod:[HQMethod OrderOrderAll] suc:^(NSDictionary *sucData) {
        [self hiddnHud];
        [_tableView.mj_header endRefreshing];
        [_tableView.mj_footer endRefreshing];
        if([sucData[kStatus]integerValue] == 1){
            NSArray *resultArr = sucData[@"data"];
            NSInteger count = 0;
            // 第一层数组
            NSMutableArray *tempArr1 = [[NSMutableArray alloc]init];
            for(NSArray *arr in resultArr){
                // 第二层数组
                NSMutableArray *tempArr2 = [[NSMutableArray alloc]init];
                for(NSDictionary *dic in arr){
                    count ++;
                    HQOrder *o = [[HQOrder alloc]init];
                    o.o_status = @"0";
                    o.danjia = dic[@"danjia"];
                    o.o_ctime = dic[@"o_ctime"];
                    o.o_id = dic[@"o_id"];
                    o.o_type = dic[@"o_type"];
                    o.o_usernam = dic[@"o_usernam"];
                    o.o_userphone = dic[@"o_userphone"];
                    o.price = dic[@"price"];
                    o.sort_v = dic[@"sort_v"];
                    [tempArr2 addObject:o];
                }
                [tempArr1 addObject:tempArr2];
            }
            if(_pageNo == 1){
                [_dataSource removeAllObjects];
                [_dataSource addObjectsFromArray:tempArr1];
                if(_dataSource.count ==0){
                    [self addNoneDataView:_tableView withText:@"列表内容为空"];
                }
                if(count >=20){
                    [self addFooter];
                }else{
                    [_tableView.mj_footer removeFromSuperview];
                }
            }else{
                [_dataSource addObjectsFromArray:tempArr1];
            }
            [self reloadStatus];
            [_tableView reloadData];
        }else{
            [self tostView:sucData[kInfo]];
        }
    } fail:^{
        [self hiddenErrorHud];
        [_tableView.mj_header endRefreshing];
        [_tableView.mj_footer endRefreshing];
    }];
}

#pragma mark 添加顶部标签
-(void)setUpTopView{
    _titleView = [[FindTitleView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44) withArray:@[@"未发订单",@"电子订单"]];
    _titleView.backgroundColor = [UIColor whiteColor];
    [_topView addSubview:_titleView];
    _titleView.itemClickBlock = ^(UIButton *button){
        if(button.tag == 1000){
            _orderStates = @"1";
            _pageNo = 1;
            _bottomView.hidden = NO;
            _bottonConstraint.constant = 49;
        }else if(button.tag == 1001){
            _pageNo = 1;
            _orderStates = @"2";
            _bottomView.hidden = YES;
            _bottonConstraint.constant = 0;
        }
        [self requestOrderList];
    };
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _dataSource.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [_dataSource[section] count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 5;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 5;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if([_orderStates isEqualToString:@"1"]){
        NotSentOrderCell *cell = [NotSentOrderCell cellWithTableView:tableView];
        cell.dataInfo = _dataSource[indexPath.section][indexPath.row];
        if([cell.dataInfo.o_status isEqualToString:@"1"]){
            [cell.selectItem setImage:[UIImage imageNamed:@"Record_Choice"] forState:UIControlStateNormal];
        }else{
            [cell.selectItem setImage:[UIImage imageNamed:@"Record_Unselected"] forState:UIControlStateNormal];
        }
        [cell.selectItem addTarget:self action:@selector(selectItem:) forControlEvents:UIControlEventTouchUpInside];
        [cell.shareButton addTarget:self action:@selector(shareOrdre:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }else{
        OrderTableViewCell *cell = [OrderTableViewCell cellWithTableView:tableView];
        cell.dataInfo = _dataSource[indexPath.section][indexPath.row];
        [cell.shareButton addTarget:self action:@selector(shareOrdre:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }
}

/**
 订单选中状态

 @param button 按钮
*/
-(void)selectItem:(HQButton *)button{
    HQOrder *o = button.dataInfo;
    if([o.o_status isEqualToString:@"1"]){
        o.o_status = @"";
    }else{
        o.o_status = @"1";
    }
    [self reloadStatus];
    [_tableView reloadData];
}

-(void)reloadStatus{
    NSMutableArray *m = [[NSMutableArray alloc]init];
    NSMutableArray *names = [[NSMutableArray alloc]init];
    for(NSArray *a in _dataSource){
        for(HQOrder *o in a){
            if([o.o_status isEqualToString:@"1"]){
                [m addObject:o.o_id];
                [names addObject:o.o_usernam];
            }
        }
    }
    if(m.count ==0){
        _selectText.text = @"请您选择后进行合并哦！";
        _hebingItem.userInteractionEnabled = NO;
        [_hebingItem setBackgroundColor:[[self colorHexValue:0xFD5900] colorWithAlphaComponent:0.5]];
       [_hebingItem setTitle:@"合并" forState:UIControlStateNormal];
    }else{
        _selectText.text =[NSString stringWithFormat:@"已选:%@",[names componentsJoinedByString:@","]];
        _hebingItem.userInteractionEnabled = YES;
        [_hebingItem setBackgroundColor:[self colorHexValue:0xFD5900]];
       [_hebingItem setTitle:[NSString stringWithFormat:@"合并(%ld个)",m.count] forState:UIControlStateNormal];
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    HQOrder *o = _dataSource[indexPath.section][indexPath.row];
    HQRecordDetailViewController *recordDetailVc = [[HQRecordDetailViewController alloc]init];
    recordDetailVc.urlStr = o.o_id;
    recordDetailVc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:recordDetailVc animated:YES];
}

/**
 分享订单的数据
 
 @param button 按钮
 */
-(void)shareOrdre:(HQButton *)button{
    _currentOrder = button.dataInfo;
    NSTimeInterval interval    = [_currentOrder.o_ctime doubleValue];
    NSDate *date               = [NSDate dateWithTimeIntervalSince1970:interval];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *time       = [formatter stringFromDate: date];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(wxShareResult:) name:@"OrderShareNotification" object:nil];
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"分享订单" message:nil preferredStyle: UIAlertControllerStyleActionSheet];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *deleteAction = [UIAlertAction actionWithTitle:@"分享至朋友圈" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"微信朋友圈分享");
        WXMediaMessage *message = [WXMediaMessage message];
        message.title = [NSString stringWithFormat:@"【%@】电子订单",[UserModelManager shopName]];
        message.description = [NSString stringWithFormat:@"请查看%@您所购买的【%@】窗帘订单信息，%@窗帘店，%@为您服务",time,_currentOrder.o_usernam,[UserModelManager shopName],[UserModelManager userName]];
        [message setThumbImage:[UIImage imageNamed:@"app_icon"]];
        WXWebpageObject *webpageObject = [WXWebpageObject object];
        webpageObject.webpageUrl = [NSString stringWithFormat:@"%@%@",kShareDomain,_currentOrder.o_id];
        message.mediaObject = webpageObject;
        SendMessageToWXReq *req = [[SendMessageToWXReq alloc]init];
        req.bText = NO;
        req.message = message;
        req.scene = WXSceneTimeline;
        [WXApi sendReq:req];
        
    }];
    UIAlertAction *archiveAction = [UIAlertAction actionWithTitle:@"分享至微信好友" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"微信分享");
        WXMediaMessage *message = [WXMediaMessage message];
        message.title = [NSString stringWithFormat:@"【%@】电子订单",[UserModelManager shopName]];
        message.description = [NSString stringWithFormat:@"请查看%@您所购买的【%@】窗帘订单信息，%@窗帘店，%@为您服务",time,_currentOrder.o_usernam,[UserModelManager shopName],[UserModelManager userName]];
        [message setThumbImage:[UIImage imageNamed:@"app_icon"]];
        WXWebpageObject *webpageObject = [WXWebpageObject object];
        webpageObject.webpageUrl = [NSString stringWithFormat:@"%@%@",kShareDomain,_currentOrder.o_id];
        message.mediaObject = webpageObject;
        SendMessageToWXReq *req = [[SendMessageToWXReq alloc]init];
        req.bText = NO;
        req.message = message;
        req.scene = WXSceneSession;
        [WXApi sendReq:req];
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:deleteAction];
    [alertController addAction:archiveAction];
    alertController.popoverPresentationController.sourceView = [UIApplication sharedApplication].keyWindow.rootViewController.view;
    alertController.popoverPresentationController.sourceRect = CGRectMake(0,0,1.0,1.0);
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
    
}

#pragma mark 微信分享逻辑
-(void)wxShareResult:(NSNotification *)noti{
    NSInteger requestMark = [noti.userInfo[@"wxResult"]integerValue];
    switch (requestMark) {
        case WXSuccess:{
            NSLog(@"分享订单的数据: %@",_currentOrder);
            if([_orderStates isEqualToString:@"1"]){
                [self showHudText:@""];
                [HQNetWork requetParam:[HQParam savestateWithUserId:[UserModelManager userID] withOID:_currentOrder.o_id] withMethod:[HQMethod orderSavestate] suc:^(NSDictionary *sucData) {
                    [self hiddnHud];
                    if([sucData[kStatus]integerValue] == 1){
                        [self tostView:@"订单操作成功，请到已发订单查看!"];
                        _pageNo = 1;
                        [self requestOrderList];
                    }else{
                        [self tostView:sucData[kInfo]];
                    }
                } fail:^{
                    [self hiddenErrorHud];
                }];
            }else{
                [self tostView:@"订单分享成功!"];
            }
        }break;
        default:{
            [self tostView:@"取消分享"];
        }break;
    }
}

// 删除订单
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    HQOrder *o = _dataSource[indexPath.section][indexPath.row];
    [self deleteOrder:o.o_id];
}

-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    return [NSString stringWithFormat:@"第%ld组",section+1];
}

// 搜索订单
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [searchBar resignFirstResponder];
    NSLog(@"在这里搜索数据吧");
}


/**
 删除订单接口
 
 @param orderID 订单ID
 */
-(void)deleteOrder:(NSString *)orderID{
    [self showHudText:@"删除中..."];
    [HQNetWork requetParam:[HQParam orderOrderdelWithOId:orderID] withMethod:[HQMethod orderOrderdel] suc:^(NSDictionary *sucData) {
        [self hiddnHud];
        if([sucData[kStatus]integerValue] == 1){
            [self tostView:@"订单删除成功"];
            [self requestOrderList];
        }else{
            [self tostView:sucData[kInfo]];
        }
    } fail:^{
        [self hiddenErrorHud];
    }];
}

/**
 合并订单

 @param sender 按钮
 */
- (IBAction)hebingItem:(id)sender {
    NSMutableArray *m = [[NSMutableArray alloc]init];
    for(NSArray *a in _dataSource){
        for(HQOrder *o in a){
            if([o.o_status isEqualToString:@"1"]){
                [m addObject:o.o_id];
            }
        }
    }
    if(m.count >0){
        NSString *o_ids = [m componentsJoinedByString:@","];
        [self showHudText:@"合并中..."];
        [HQNetWork requetParam:[HQParam set_order_group:[UserModelManager userID] o_ids:o_ids] withMethod:[HQMethod set_order_group] suc:^(NSDictionary *sucData) {
            [self hiddnHud];
            if([sucData[kStatus]integerValue] == 1){
                [self tostView:@"订单合并成功"];
                _pageNo = 1;
                [self requestOrderList];
            }else{
                [self tostView:sucData[kInfo]];
            }
        } fail:^{
            [self hiddenErrorHud];
        }];
    }else{
        [self tostView:@"请选择要合并的订单"];
    }
}

@end
